package com.itheima.dubbo.api;

import com.itheima.dubbo.utils.IdWorker;
import com.itheima.model.enums.CommentType;
import com.itheima.model.enums.VideoType;
import com.itheima.model.mongo.Comment;
import com.itheima.model.mongo.FocusUser;
import com.itheima.model.mongo.Movement;
import com.itheima.model.mongo.Video;
import com.itheima.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Date;
import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {
        video.setVid(idWorker.getNextId("video"));
        video.setCreated(System.currentTimeMillis());
        mongoTemplate.save(video);
        return video.getId().toString();
    }

    @Override
    public List<Video> finByVids(List<Long> vids) {
        return mongoTemplate.find(Query.query(Criteria.where("vid").in(vids)), Video.class);
    }

    @Override
    public List<Video> findRandom(int page, Integer pagesize) {
        return mongoTemplate.find(new Query().with(PageRequest.of(page - 1, pagesize, Sort.by(Sort.Order.desc("created")))), Video.class);
    }

    /*关注*/
    @Override
    public void saveFocusUser(FocusUser followUserId) {
        followUserId.setId(ObjectId.get());
        followUserId.setCreated(System.currentTimeMillis());
        mongoTemplate.save(followUserId);

    }

    /*判断是否关注*/
    @Override
    public Boolean hasVideo(Long followUserId, Long userId, VideoType videoType) {
        Query query = Query.query(Criteria.where("userId").is(userId).
                and("loveCount").is(videoType.getType()).and("followUserId").is(followUserId));
        return mongoTemplate.exists(query, FocusUser.class);
    }

    @Override
    public void delete(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        mongoTemplate.remove(query, FocusUser.class);
    }

    @Override
    public Boolean hasLike(String id, Long userId, VideoType hasLiked) {
        Query query = Query.query(Criteria.where("id").is(id).and("userId").is(userId).and("hasLiked").is(hasLiked));
        return mongoTemplate.exists(query, VideoVo.class);
    }

    @Override
    public void updateById(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = new Update();
        update.inc("likeCount", 1);
        FindAndModifyOptions op = new FindAndModifyOptions();
        op.returnNew(true);
        Video video = mongoTemplate.findAndModify(query, update, op, Video.class);
    }

    @Override
    public void deteleById(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = new Update();
        update.inc("likeCount", -1);
        FindAndModifyOptions op = new FindAndModifyOptions();
        op.returnNew(true);
        Video video = mongoTemplate.findAndModify(query, update, op, Video.class);
    }


    @Override
    public Long count(Long uid) {
        Query query = Query.query(Criteria.where("userId").is(uid));
        return mongoTemplate.count(query, Video.class);
    }

    @Override
    public void saveComment(Comment comment) {
        /*保存评论*/

        //将Movement中的评论/点赞/喜欢数+1
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));

        Update update = new Update();
        if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        FindAndModifyOptions op = new FindAndModifyOptions();
        op.returnNew(true);
        Video resMovement = mongoTemplate.findAndModify(query, update, op, Video.class);
        //保存评论
        if (resMovement != null) {
            comment.setPublishUserId(resMovement.getUserId());
        }
        comment.setCreated(System.currentTimeMillis());
        mongoTemplate.save(comment);//保存评论数
    }

    @Override
    public List<Video> findById(Long uid, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(uid))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize).limit(pagesize);
        //查询
        List<Video> videos = mongoTemplate.find(query, Video.class);
        return videos;
    }

    @Override
    public Long countType(Integer type) {
        Query query = Query.query(Criteria.where("seeType").is(type));
        return mongoTemplate.count(query, Video.class);
    }
}
